﻿using Android.Content;
using Android.Net.Http;
using Android.Print;
using Android.Webkit;
using Java.Net;
using System.Net;
using Xamarin.Forms;
using System.Threading.Tasks;
using Android.App;
using Xamarin.Essentials;
using System.IO;
using System.Diagnostics;
using ZXXFAPP.Views;
using ZXing.Net.Mobile.Forms;

namespace ZXAPP
{
    public class CustomWebChromeClient : WebChromeClient
    {
        public override void OnPermissionRequest(PermissionRequest request)
        {
            request.Grant(request.GetResources());
        }
    }
    public class CustomWebViewClient : WebViewClient
    {
        private Android.Webkit.WebView _webView;

        public CustomWebViewClient(Android.Webkit.WebView webView)
        {
            _webView = webView;
            //在这里没法接收到消息，因为这个类不是继承自Page
            //MessagingCenter.Subscribe<ScanPage,string>(this, "BarcodeScanResult", (Sender,barcode) =>
            //{
            //    // 在这里，你可以使用 JavaScript 与 WebView 交互，将条形码传递给网页
            //    //var script = $"document.getElementById('barcodeInput').value = '{barcode}';";
            //    //var script = $"window.vueApp.setSearchValue('{barcode}');";
            //    //var script = $"alert(\"这是一个警告框\");";
            //    Trace.WriteLine("barcode aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: " + barcode);
            //    var script = $"window.receiveAppMsg('{barcode}');";
            //    _webView.EvaluateJavascript(script, null);
            //});

            //测试代码，直接发送消息，不调用扫描页面
            //MessagingCenter.Subscribe<WebViewClient, string>(this, "BarcodeScanResult", (sender, barcode) =>
            //{
            //    Trace.WriteLine("barcode: " + barcode);
            //    var script = $"window.receiveAppMsg('123321');";
            //    _webView.EvaluateJavascript(script, null);
            //});
        }
        public override bool ShouldOverrideUrlLoading(Android.Webkit.WebView view, IWebResourceRequest request)
        {
            string url = request.Url.ToString();
            if (url.StartsWith("app://"))
            {
                var pageName = url.Substring(6);
                //var pages = Navigation.NavigationStack;
                // 根据页面的名字导航到不同的页面
                if (pageName == "scanpage")
                {
                    Trace.WriteLine("going to scan page");
                    Device.BeginInvokeOnMainThread(async () =>
                    {
                        //await Shell.Current.GoToAsync("//LogonPage");
                        //ZXingScannerPage scanPage;
                        //scanPage = new ZXingScannerPage();

                        //scanPage.OnScanResult += (result) =>
                        //{
                        //    scanPage.IsScanning = false;
                        //    Device.BeginInvokeOnMainThread(async () =>
                        //    {
                        //        await Shell.Current.Navigation.PopModalAsync();
                        //        MessagingCenter.Send<ZXingScannerPage, string>(scanPage, "BarcodeScanResult", result.Text);
                        //        //await DisplayAlert("Scanned Barcode", result.Text + " , " + result.BarcodeFormat + " ," + result.ResultPoints[0].ToString(), "OK");
                        //    });
                        //};
                        //await Shell.Current.Navigation.PushModalAsync(scanPage);
                        await Shell.Current.Navigation.PushModalAsync(new ScanPage());

                        //测试，直接从c#发送消息，不调用扫描页面,发现是OK的
                        //MessagingCenter.Send<WebViewClient, string>(this, "BarcodeScanResult", "123321");

                    });
                }
                return true; 
            }

            return false; // 没有处理 URL 加载，让 WebView 正常加载
        }

        public override void OnReceivedSslError(Android.Webkit.WebView view, SslErrorHandler handler, SslError error)
        {
            handler.Proceed();
        }
    }

    public class MyDownloadListener : Java.Lang.Object, IDownloadListener
    {
        public void OnDownloadStart(string url, string userAgent, string contentDisposition, string mimetype, long contentLength)
        {
            try
            {
                DownloadManager.Request request = new DownloadManager.Request(Android.Net.Uri.Parse(url));
                request.AllowScanningByMediaScanner();
                request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);
                // if this path is not create, we can create it.
                string thmblibrary = FileSystem.AppDataDirectory + "/download";
                if (!Directory.Exists(thmblibrary))
                    Directory.CreateDirectory(thmblibrary);
                request.SetDestinationInExternalFilesDir(Android.App.Application.Context, FileSystem.AppDataDirectory, "download");
                DownloadManager dm = (DownloadManager)Android.App.Application.Context.GetSystemService(Android.App.Application.DownloadService);
                dm.Enqueue(request);

            }
            catch (System.Exception err)
            {
                throw;
            }

        }
    }

}